<template>
  <!-- 车辆基本信息 -->
  <div class="vehicleinfo">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
      >
        <!-- 左上方菜单内容 -->
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            v-if="permission.vehicleinfo_delete"
            @click="handleDelete"
          >
            删 除
          </el-button>
          <el-button
            type="success"
            size="small"
            plain
            icon="el-icon-upload2"
            @click="handleImport"
          >
            导 入
          </el-button>
          <el-button
            type="warning"
            size="small"
            plain
            icon="el-icon-download"
            @click="handleExport"
          >
            导 出
          </el-button>
        </template>
      </avue-crud>

      <!-- 导入弹窗 -->
      <el-dialog
        title="车辆基本信息导入"
        append-to-body
        :visible.sync="excelBox"
        width="555px"
      >
        <avue-form
          :option="excelOption"
          v-model="excelForm"
          :upload-after="uploadAfter"
          :upload-before="beforeUpload"
          :upload-error="uploadError"
        >
          <template slot="excelTemplate">
            <el-button type="primary" @click="handleTemplate">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  getUnbindLocationCards,
  getUnbindCarList
} from "@/api/useronduty/vehicleinfo";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";

export default {
  data() {
    return {
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        viewBtn: true,
        selection: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: "车牌号码",
            prop: "cph",
            align: "center",
            search: true,
            rules: [
              {
                required: true,
                message: "请输入车牌号",
                trigger: "blur"
              }
            ]
          },
          {
            label: "运输公司",
            prop: "ysgs",
            align: "center",
            search: true,
            rules: [
              {
                required: true,
                message: "请输入运输公司",
                trigger: "blur"
              }
            ]
          },
          {
            label: "运输人",
            prop: "ysr",
            align: "center",
            rules: [
              {
                required: true,
                message: "请输入运输人",
                trigger: "blur"
              }
            ]
          },
          {
            label: "运输人身份证",
            prop: "ysrsfz",
            align: "center",
            rules: [
              {
                required: true,
                message: "请输入运输人身份证",
                trigger: "blur"
              }
            ]
          },
          {
            label: "运输人电话",
            prop: "ysrdh",
            align: "center",
            rules: [
              {
                required: true,
                message: "请输入运输人电话",
                trigger: "blur"
              }
            ]
          },
          {
            label: "押运人",
            prop: "yyr",
            align: "center"
          },
          {
            label: "押运人身份证",
            prop: "yyrsfz",
            hide: true
          },
          {
            label: "押运人电话",
            prop: "yyrdh",
            hide: true
          },
          {
            label: "IC卡号",
            prop: "ickh",
            align: "center"
          },
          {
            label: "定位卡号",
            prop: "dwkh",
            hide: true,
            type: "select",
            dicData: [],
            props: {
              label: "bqh",
              value: "id"
            }
          }
        ]
      },
      // 导入
      excelBox: false,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            showFileList: false,
            span: 24,
            propsHttp: {
              fileName: "multipartFile",
              res: "data"
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/basicInformation/vehicleinfo/import"
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24
          }
        ]
      },
      isFailed: false
    };
  },
  mounted() {
    this.onLoad(this.page);
  },
  computed: {
    ...mapGetters(["permission"]),

    // 车辆基本信息列表按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.vehicleinfo_add, false),
        viewBtn: this.vaildData(this.permission.vehicleinfo_view, false),
        delBtn: this.vaildData(this.permission.vehicleinfo_delete, false),
        editBtn: this.vaildData(this.permission.vehicleinfo_edit, false)
      };
    },

    // 车辆基本信息列表勾选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    // 弹出导入框
    handleImport() {
      this.excelBox = true;
    },

    // 导入前判断
    beforeUpload(file, done, loading) {
      this.isFailed = false;
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = testmsg === "xls";
      const extension2 = testmsg === "xlsx";
      if (!extension && !extension2) {
        this.$message.warning("请上传 .xls,.xlsx 标准格式文件!");
        loading();
      } else {
        done();
      }
    },

    // 模板下载
    handleTemplate() {
      let str =
        this.$UploadUrl + "/hg/file/template/basicVehicleInformation.xlsx";
      window.open(str);
    },

    // 导入失败后
    uploadError(error, column) {
      console.log(error, column);
      this.isFailed = true;
    },

    // 导入成功后
    uploadAfter(res, done) {
      done();
      if (this.isFailed === true) {
        return;
      }
      this.excelBox = false;
      this.$message.success("上传成功");
      this.cancle();
    },

    // 取消
    cancle() {
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },

    // 点击导出按钮
    handleExport() {
      this.$confirm("是否导出车辆基本信息?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let cph =
          this.query.cph === undefined || this.query.cph === null
            ? ""
            : this.query.cph;
        let ysgs =
          this.query.ysgs === undefined || this.query.ysgs === null
            ? ""
            : this.query.ysgs;
        window.open(
          `/api/basicInformation/vehicleinfo/export?${
            this.website.tokenHeader
          }=${getToken()}&cph=${cph}&ysgs=${ysgs}`
        );
      });
    },

    // 新增
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },

    // 修改
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },

    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
        });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          this.$refs.crud.toggleSelection();
        });
    },

    // 打开查看、编辑、新增弹窗前
    beforeOpen(done, type) {
      if (type === "add") {
        getUnbindLocationCards().then(res => {
          let dwkhColumn = this.findObject(this.option.column, "dwkh");
          dwkhColumn.dicData = res.data;
        });
      } else {
        getDetail(this.form.id)
          .then(res => {
            this.form = res.data.data;
          })
          .then(() => {
            getUnbindCarList(this.form.id).then(res => {
              let dwkhColumn = this.findObject(this.option.column, "dwkh");
              dwkhColumn.dicData = res.data;
            });
          });
      }
      done();
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变事件
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },

    // 换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 获取表格数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style lang="scss" scpoed>
.vehicleinfo {
  .avue-crud {
    .avue-crud__search {
      .avue-form__row:nth-child(1) {
        .el-form-item__label {
          text-align: unset;
        }
      }
    }
  }
}

.avue-dialog {
  .el-dialog {
    .avue-group {
      .avue-form__group {
        .el-form-item {
          .el-form-item__label {
            width: 110px !important;
          }

          .el-form-item__content {
            margin-left: 110px !important;
          }
        }
      }
    }
  }
}
</style>